package edu.ctbu.insurance.service.userEmail.impl;

import edu.ctbu.insurance.bean.User;
import edu.ctbu.insurance.mapper.UserMapper;
import edu.ctbu.insurance.service.UserService;
import edu.ctbu.insurance.service.userEmail.EmailService;
import edu.ctbu.insurance.service.userEmail.UserVoToUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.*;
import org.springframework.mail.javamail.*;
import edu.ctbu.insurance.vo.UserVo;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
@Transactional
public class EmailServiceImpl implements EmailService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSenderImpl mailSender;

    // application.properties配置的值
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 给前端输入的邮箱，发送验证码
     */
    @Override
    public String sendEmail(String email, HttpSession httpSession) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            // 生成随机数
            String code = randomCode();
            // 将随机数放置到session中
            httpSession.setAttribute("email", email);
            httpSession.setAttribute("code", code);

            simpleMailMessage.setSubject("验证码邮件"); // 主题
            simpleMailMessage.setText("您收到的验证码是："+code); // 内容
            simpleMailMessage.setFrom("2464568400@qq.com"); // 发件人
            simpleMailMessage.setTo(email); // 收件人
            mailSender.send(simpleMailMessage); // 发送

            return code;
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    @Override
    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for(int i = 0;i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * 检验验证码
     */
    @Override
    public String emailLogin(String emailCode, HttpSession httpSession) {
        // 获取session中的验证信息
        String email = (String) httpSession.getAttribute("email");
        String code = (String) httpSession.getAttribute("code");

        if (code.equals(emailCode)) {
            return email;
        } else {
            return "error";
        }
    }
}
